//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package notice_serv

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/anypb"
)

var _rdb *redis.Client

const _USER_NOTICE_CHANNEL_PREFIX = "usernotice:"

func Init(rdb *redis.Client) error {
	_rdb = rdb
	return nil
}

func SubscribeToUser(ctx context.Context, userId string) (*redis.PubSub, error) {
	if _rdb == nil {
		return nil, fmt.Errorf("no redis connection")
	}
	channel := _USER_NOTICE_CHANNEL_PREFIX + userId
	sub := _rdb.Subscribe(ctx, channel)
	return sub, nil
}

func PublishToUser(userId string, notice proto.Message) error {
	if _rdb == nil {
		return fmt.Errorf("no redis connection")
	}
	any, err := anypb.New(notice)
	if err != nil {
		return err
	}
	data, err := proto.Marshal(any)
	if err != nil {

		return err
	}
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	channel := _USER_NOTICE_CHANNEL_PREFIX + userId
	return _rdb.Publish(ctx, channel, data).Err()
}
